<template lang="jade">
div#app
	div.return-bar
		i.iconfont(@click="back()") &#xe668;
		有喜财富新用户注册
	div.login-from.detail_top
		div
			img(src="../../assets/images/logo.png",  style="width:100%")
		validator(name="validation1")
			div.mb10
				div.login-control
					div.control
						span 手机号
						input(v-model="username",placeholder="请输入您的手机号码",v-validate:username="{required:true, maxLength: 10}",maxLength="11")
					div.control
						span 图片验证码
						input(v-model="verify",placeholder="请输入验证码",v-validate:code="{required:true, maxLength: 4}",maxLength="4")
						img.verify(v-show="verify_img.show", src="{{verify_img.src}}", @click="reloadImg")

					div.control
						span 验证码
						input(v-model="code",placeholder="请输入验证码",v-validate:code="{required:true, maxLength: 4}",maxLength="4")
						button.send-code(v-bind:class="timecls", @click="sendVCode()") {{smsData.btnTxt}}


					div.control
						span 密码
						input(v-show=" !showPWD ", v-model="password",type="password",placeholder="设置密码",v-validate:password="{required:true}")
						input(v-show=" showPWD ", v-model="password",type="text",placeholder="设置密码",v-validate:password="{required:true}")
						i.iconfont.icon-eyesclose(@click="switchKw()") {{{iconString}}}

					div.control
						span 确认密码
						input(v-model="repassword",type="password",placeholder="确认密码",v-validate:repassword="{required:true}")
					div.control
						span 推荐人(选填)
						input(type="text",placeholder="推荐人（选填）",v-model="reference")

					div(style="padding-top:20px;font-size:14px;vertical-align: middle;")
						label
							input(input type="checkbox", v-model="terms_input", style="width:  auto;vertical-align: middle;")
							有喜财富注册协议
						a(style="margin-left:10px", herf="javascript:void(0);",  @click="showTerms") 查看


					div
						button.p_btn.postIt(type="button", @click="regSumbit()") 注册
					div.link
						a.relation-link(v-link="{ path: '/forget-pwd' }") 忘记密码
						span.spr |
						a.relation-link.red(v-link="{ path: '/login' }") 立即登录


		div.neworder(v-show="  items ")
			dl
				dt {{items.name}}
				dd
					span(style="width:70%;")
						em 年收益率
						b {{items.borrow_apr}}%
							strong  {{items.borrow_period}}个月/100元起投
					span(style="width:30%;")
						a.input(v-link="{ name: 'detail', params: { detailId: items.borrow_nid } }") 立即摘标


	alert.custom_alert(:show.sync="alertMsg.show", title="提示", button-text="确定") {{alertMsg.msg}}
	common-dialog(v-show="showDialog",  @update:setparent=" setparent " , :close="true")
		terms
</template>


<script>


import '../../assets/sass/user/login.scss'
import {c_reg_verify_img, c_base64, Api_Reg,Api_Reg_Code} from '../../config/api'
import {Loading, Alert} from 'vux'
var time_work = null;

import CommonDialog from "../../components/dialog";  //弹窗插件
import Terms from "./terms";
import { mapGetters } from 'vuex'

export default {

	data () {
		return {


			terms_input:true,
			recommend_uid: '',
			username: localStorage.getItem("tel") || '',
			code: '',

			//img_src:'',
			//show_img:true,
			verify_img: { show:true, src:'' },
            smsData: {stop:false, disableBtn:false,btnTxt:"获取动态码",timer:0},
			alertMsg: { msg:'',show:false},
			verify:'',
			password: '',
			repassword: '',
			rec_name: '',
			busy: false,
			iconString:'&#xe712;',
			showPWD:false,
			reference:'',
			timecls:'',
			//timemsg:'获取验证码',
			timer: 10,       //默认倒数30秒
			stop : false,   //默认是停止的，但界面加载之后会变成false
			Interval:null  //setInterval的对象
		}
	},

    computed: {
      ...mapGetters([
		  'showDialog'
      ])
	},

	components:{
		CommonDialog,
		Terms,
		Loading,
		Alert
	},
	methods: {
		setparent(params){
			//this.showDialog = params.status;
			this.$store.dispatch('setShowDialog', params.status)
		},

		reloadImg(){
			/*this.$http({url: c_img_verify, method: 'GET'}).then(function (response) {
				this.img_src = c_img_verify;
			});*/

			this.verify_img.show = false;
			this.verify_img.src = '';


			var that = this;

			var timestamp = Date.parse(new Date());
			timestamp = timestamp / 1000;
			var rkey = that.global.r_key()
			var pkey = that.global.p_key()

			//this.img_src = c_img_verify
			//time_work = setInterval(function(){
			setTimeout(function(){
				//that.show_img = true;
				that.verify_img.show = true;
				that.verify_img.src = c_reg_verify_img+'&t='+timestamp+'&r_key='+rkey+'&p_key='+pkey
			},1);

		},

		back(){
			window.history.back();
		},


		/* update () {
			if(this.timer <= 0)
			{
				//this.timer = 10;
				this.timecls='';
				this.stop = false;
				this.timemsg = "获取验证码";
			}
			else{
				this.timecls='gray';
				this.timer--;
				this.timemsg = '剩余'+this.timer+'秒';
			}
		},

		startTimer () {
			//console.log('start');
			//如果是false就开始倒计时，如果是true就停止倒计时
			clearInterval(this.Interval);
			this.timer = 60;
			if(this.stop == false)
			{
				this.Interval = setInterval(this.update,1000);
			}
			else
			{
				clearInterval(this.Interval);
			}
			this.stop = !this.stop;
		}, */



	    updateSms () {

	    	console.log('get ')
	        if(this.smsData.timer <= 0)
	        {
				this.stopTimeCount('重新发送');
				this.timecls='';
	        }
	        else{
				this.timecls='gray';
	            this.smsData.timer--;
	            this.smsData.btnTxt = '剩余'+this.smsData.timer+'秒';
	        }

	    },

		stopTimeCount(str){
			clearInterval(time_work);
			this.smsData.timer  = 0;
			this.smsData.stop = false;
			this.smsData.disableBtn = false;
			this.smsData.btnTxt = str;
			//str = '重新发送'
		},

	    startTimer () {
			clearInterval(time_work);
			//if(this.msn.timer>0) return;
			if(this.smsData.timer == 0)	this.smsData.timer = 60;
	        if(this.smsData.stop == false)
	        {
				time_work = setInterval(this.updateSms,1000);
	        }
	        else
	        {
				clearInterval(time_work);
	        }

		},


		switchKw(){
			if(this.iconString == '&#xe712;')
				this.iconString = '&#xe648;'
			else
				this.iconString = '&#xe712;'
			this.showPWD = !this.showPWD;
		},

		regSumbit: function () {


			if(this.terms_input == false){

				this.alertMsg.msg = '请钩选并同意有喜财富注册协议, 谢谢合作!'
				this.alertMsg.show = true;
				return false;
			}

			if (this.$validation1.invalid || this.busy) {
				return false;
			}

			if(this.password != this.repassword){
				alert('两次密码输入不一致！')
				return false;
			}



			this.busy = true, this.$store.dispatch('setShowLoading', true);
			var data = {'verify':this.verify, 'phone': this.username,'code':this.code,'password':this.password,'rec_name':this.reference}
			this.$http.post(Api_Reg, data,'').then(function (response) {
				var rs = response.data;
				alert(rs.msg)
				this.busy = false, this.$store.dispatch('setShowLoading', false);
				if(rs.status){
					localStorage.setItem("tel", this.username);
					sessionStorage.setItem("login", true);
					//sessionStorage.setItem("loan", false)
					this.$router.go('/openAccount')
				}else{
					this.reloadImg();
					this.verify='';
				}
			});
		},

		sendVCode: function () {

			//console.log(this.stop)

			if(this.verify=='' || this.stop || this.busy) {
				return false;
			}
			if(!this.username){
				alert('请输入您的手机号！')
				return false;
			}
			if(this.smsData.disableBtn) return;
			this.smsData.disableBtn = true, this.startTimer();
			this.getCode();
		},

		getCode(){
			if(this.busy) return;
			//this.$store.dispatch('setShowLoading', true);
			this.busy = true;
			var data = {'verify':this.verify, 'phone': this.username}
			this.$http.post(Api_Reg_Code, data,'').then(function (response) {
				//this.$store.dispatch('setShowLoading', false);
				var rs = response.data;
				//alert(rs.msg)
				this.busy = false;
				if(!rs.status){
					this.reloadImg();
					this.verify='';
					this.stopTimeCount('重新发送');
					this.alertMsg.msg = rs.msg
					this.alertMsg.show = true;
				}
			});
		},


		showTerms(){
			this.$store.dispatch('setShowDialog',  true)
		},


		jm(){
			this.$http({url: c_base64+'&code='+this.recommend_uid, method: 'GET'}).then(function (response) {
				this.reference = response.data.username  || '';
			});
		}
	},
	route: {
		activate ( transition ) {
			var timestamp = Date.parse(new Date());
			timestamp = timestamp / 1000;

			var rkey = this.global.r_key()
			var pkey = this.global.p_key()

			this.verify_img.src = c_reg_verify_img+'&t='+timestamp+'&r_key='+rkey+'&p_key='+pkey;


			this.from = transition.to.query.from
			this.recommend_uid = transition.to.query.recommend_uid || ''
			if(this.recommend_uid!==""){
				this.jm();
			}
			//console.log(this.from)
			if(sessionStorage.getItem("login")){
				this.$route.router.go('/')
			}else{
				transition.next();
			}

			this.$store.dispatch('setShowDialog',  true)
		}
	}
}
</script>
